#include <list>
#include <iostream>
using namespace std;

//!< c1.merge(c2)
//! 合并2个有序的链表并使之有序,从新放到c1里,释放c2。
//!< c1.merge(c2,comp)
//!   合并2个有序的链表并使之按照自定义规则排序之后从新放到c1中,释放c2。
int list_merge()
{
    list<int> a1{1,2,3}, a2{4,5,6};
    a1.merge(a2);
    list<int>::iterator it;
    cout << "a1.merge(a2):";
    for(it = a1.begin();it!=a1.end();it++){
        cout << *it << " ";
    }
    cout << endl;

    a2.merge(a1,[](int n1,int n2){return n1<n2;});
    cout << "a2.merge(a1,comp):";
    for(it = a2.begin();it!=a2.end();it++){
        cout << *it << " ";
    }
    cout << endl;

    return 0;
}

//!< c1.splice(c1.beg,c2)
//!    将c2连接在c1的beg位置,释放c2
int test_splice_two()
{
    cout << "\n" << __FUNCTION__ << ":\n";
    list<int> a1{1,2,3},a2{4,5,6};
    a1.splice(a1.begin(), a2);
    list<int>::iterator it;
    cout << "a1.merge(a2):";
    for(it = a1.begin();it!=a1.end();it++){
        cout << *it << " ";
    }
    cout << endl;
    cout << "a2.size() = " << a2.size() << endl;

    return 0;
}

//!< c1.splice(c1.beg,c2,c2.beg)
//!  将c2的beg位置的元素连接到c1的beg位置，并且在c2中施放掉beg位置的元素
int test_splice_three()
{
    cout << "\n" << __FUNCTION__ << ":\n";
    list<int> a1{1,2,3},a2{4,5,6};
    a1.splice(a1.begin(), a2, ++a2.begin());
    list<int>::iterator it;
    cout << "a1.merge(a2):";
    for(it = a1.begin();it!=a1.end();it++){
        cout << *it << " ";
    }
    cout << endl;

    cout << "a2 = \n";
    for(it = a2.begin();it!=a2.end();it++){
        cout << *it << " ";
    }

    return 0;
}

//!< c1.splice(c1.beg,c2,c2.beg,c2.end)
//!   将c2的[beg,end)位置的元素连接到c1的beg位置并且释放c2的[beg,end)位置的元素
int test_splice_four()
{
    cout << "\n" << __FUNCTION__ << ":\n";
    list<int> a1{1,2,3},a2{4,5,6};
    a1.splice(a1.begin(), a2, a2.begin(), a2.end());
    list<int>::iterator it;
    cout << "a1.merge(a2):";
    for(it = a1.begin();it!=a1.end();it++){
        cout << *it << " ";
    }
    cout << endl << "a2 = \n";

    for(it = a2.begin();it!=a2.end();it++){
        cout << *it << " ";
    }
    cout << endl;

    return 0;
}

int main(int argc, char *argv[])
{
    test_splice_two();
    test_splice_three();
    test_splice_four();

    return 0;
}
